<template>
    <div>
        <el-page-header icon="" content="添加用户" title="用户管理"></el-page-header>

        <el-form ref="userFormRef"  status-icon :model="userForm" :rules="userFormRules" label-width="auto" class="demo-ruleForm">

            <el-form-item label="用户名" prop="username">
                <el-input v-model="userForm.username" />
            </el-form-item>

            <el-form-item label="密码" prop="password">
                <el-input v-model="userForm.password" type="password" />
            </el-form-item>

            <el-form-item label="角色" prop="role">
                <el-select v-model="userForm.role" style="width: 150px">
                    <el-option v-for="item in options" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>

            <el-form-item label="个人简介" prop="introduction">
                <el-input v-model="userForm.introduction" type="textarea"/>
            </el-form-item>

            <el-form-item label="头像" prop="avatar">
                <Upload :avatar = "userForm.avatar" @fileChange="handleChange"></Upload>
            </el-form-item>

            <el-form-item class="label">
                <el-button type="primary" @click="submitForm()" style="margin: 0 auto;">添加用户</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import {ref,reactive} from 'vue'
import {useRouter} from 'vue-router'
import Upload from '@/components/upload/Upload.vue';
import upload from '@/util/upload'

const userFormRef = ref()
const router = useRouter()
const userForm = reactive({
    username:"",
    password:"",
    role:2, //1 管理员 2 编辑
    introduction:"",
    avatar:"",
    gender:0,
    file:null
})

//选择完头像后的回调
const handleChange = (file) =>{
    userForm.avatar = URL.createObjectURL(file)
    userForm.file = file
} 

const submitForm = ()=>{
    userFormRef.value.validate(async (valid)=>{
        if(valid){
            await upload('/adminapi/user/add',userForm)
            router.push('/user-manage/userlist')
        }
    })
}

const options = [
    {
        label: "管理员",
        value: 1
    },
    {
        label: "编辑",
        value: 2
    }
]

const userFormRules = reactive({
    username: [
        { required: true, message: '输入名字', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '输入密码', trigger: 'blur' },
    ],
    role: [
        { required: true, message: '选择权限', trigger: 'blur' },
    ],
    introduction: [
        { required: true, message: '输入介绍', trigger: 'blur' },
    ],
    avatar: [
        { required: true, message: '上传头像', trigger: 'blur' },
    ],
})
</script>

<style scoped>
.demo-ruleForm{
    margin-top: 50px;
}
</style>